package com.jiuyuan.config.security;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: hrms
 * @description:
 * @author: Feng
 * @create: 2023-02-15 08:19
 **/

public class JWTTokenUtils {
    private static final String CLAIM_KEY_USERNAME="sub";
    private static final String CLAIM_KEY_CREATED="created";
    //无法在静态字段上使用
//    @Value("${jwt.secret}")
    private static String secret = "yeb-secret";
//    @Value("${jwt.expiration}")
    private static Long expiration = 86400L;

    public static String createTokenByUserDetails(UserDetails userDetails){
        Map<String,Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME,userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED,new Date());
        return createTokenByClaims(claims);
    }

    public static String createTokenByClaims(Map<String,Object> claims){
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpiration())
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

    public static Date generateExpiration(){
        return new Date(System.currentTimeMillis()+expiration*1000);
    }

    public static Claims getClaimsByToken(String token){
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (ExpiredJwtException e){
            claims = e.getClaims();
        }
        return claims;
    }

    public static String getUsernameFromToken(String token) {
        Claims claims = getClaimsByToken(token);
        return claims.getSubject();
    }

//    public static boolean isValid(String token) {
//        Claims claims = getClaimsByToken(token);
//        return claims.getExpiration().after(new Date());
//    }
    public static boolean isValid(String token, UserDetails userDetails) {
        String username = getUsernameFromToken(token);
        return null!=username && username.equals(userDetails.getUsername()) && isValidExpire(token);

    }

    private static boolean isValidExpire(String token) {
        Claims claims = getClaimsByToken(token);
        return claims.getExpiration().after(new Date());
    }
}




























